import React, { useState, useEffect, useCallback } from "react";
import { Button, Divider } from "antd";

function useWinSize() {
  const [size, setSize] = useState({
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight,
  });
  const onResize = useCallback(() => {
    setSize({
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
    });
  }, []);
  useEffect(() => {
    window.addEventListener("resize", onResize);
    return () => {
      window.removeEventListener("resize", onResize);
    };
  }, [onResize]);
  return size;
}
const UseMyHook: React.FC = (): React.ReactElement => {
  const arr = [
    { id: 1, txt: "该组件是一个具体的功能，实现监听浏览器宽高变化。" },
    {
      id: 2,
      txt:
        "一开始会使用useState设置对应的值和方法，结合useCallback做一个缓存并封装在onResize方法中",
    },
    {
      id: 3,
      txt:
        "最后使用useEffect在首次进入时触发onResize方法开启监听，在return中执行销毁节约性能。",
    },
    {
      id: 4,
      txt: "一个完整的使用react hooks的函数式组件都应该参照这个思路去构建",
    },
    {
      id: 5,
      txt:
        "特别注意！！！这个地方不能只调size对象,必须用.width精准调用到属性，不然就报错，错误如下:",
    },
    {
      id: 6,
      txt:
        "Objects are not valid as a React child (found: object with keys {width, height}). If you meant to render a collection of children, use an array instead.",
    },
  ];
  const size = useWinSize();
  console.log(size);
  const okto = () => {
    console.log("了解了解");
  };
  return (
    <div>
      {arr.map((el) => {
        return (
          <h1 key={el.id}>
            {el.txt}
            <Button onClick={okto} style={{ marginLeft: "10px" }}>
              了解
            </Button>
          </h1>
        );
      })}
      <Divider orientation="left">OK,Got it !</Divider>
      <h1>
        当前浏览器窗口宽高分别为：{size.width}---{size.height}
      </h1>
    </div>
  );
};
export default UseMyHook;
